import Vue from 'vue'
import Vuex from 'vuex'

import {login} from "@/api/login";
import {getUserInfo} from "@/api/user";

Vue.use(Vuex)
export default {
    state: {
        token: '',
        userInfo: {},
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
            localStorage.setItem("token", token)
        },
        SET_USERINFO: (state, userInfo) => {
            state.userInfo = userInfo
        }
    },
    actions: {
        // user login
        login({commit}, userInfo) {
            const {username, password, code, token} = userInfo
            return new Promise((resolve, reject) => {
                const data = {
                    username,
                    password,
                    code,
                    token
                }
                login(data).then(response => {
                    const jwt = response.data
                    commit('SET_TOKEN', jwt)
                    resolve(response.data)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        //获取用户信息
        getUserInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    const data = res.data
                    if (!data) {
                        reject('Verification failed, please Login again.')
                    }
                    if (data.avatar !== null){
                        data.avatar = '/'+data.avatar
                    }
                    commit('SET_USERINFO', data)
                    resolve(data)
                }).catch(error => {
                    reject(error)
                })
            })
        }
    }
}
